/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.push;

import org.jivesoftware.smack.XMPPException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.MessageStatistics;
import com.foreveross.bsl.PushMessage;
import com.foreveross.bsl.openfire.OpenfireClient;
import com.foreveross.bsl.openfire.ReceiveStatisticMessageListener;

/**
 * xxx
 * 
 * @author Wangyi
 * @version v1.0
 * 
 * @date 2013-12-10
 * 
 */
public class OpenfirePushClient extends PushClient {

	private static final Logger log = LoggerFactory.getLogger(OpenfirePushClient.class);
	private final OpenfireClient openfirec;
	private final ReceiveStatisticMessageListener receiveStatisticMessageListener;

	/**
	 * @param url
	 * @param deviceId
	 * @param appId
	 */
	public OpenfirePushClient(final MessageStatistics msgStat, OpenfireClient openfirec, String url) {
		super(url);
		this.openfirec = openfirec;
		this.receiveStatisticMessageListener=new ReceiveStatisticMessageListener(msgStat){
			protected void handlePushMessage(PushMessage pmsg) {
				try {
					boolean ret=OpenfirePushClient.this.receipt(pmsg.getId());
					msgStat.countReceipt(ret);
				} catch (Exception e) {
					log.error("回执推送出错！", e);
				} 
			}
		};
		this.openfirec.setReceiveStatisticMessageListener(receiveStatisticMessageListener);
	}
	
	/* (non-Javadoc)
	 * @see com.foreveross.bsl.push.PushClient#getToken()
	 */
	@Override
	protected String getToken() {
		try {
			this.openfirec.connect();
			this.openfirec.login();
			return this.openfirec.getConnection().getUser();
		} catch (XMPPException e) {
			throw new RuntimeException(e);
		}
	}

}
